package com.fei.myback.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fei.myback.entity.LoginUser;
import com.fei.myback.pojo.User;
import com.fei.myback.service.User.UserServiceImpl;
import com.fei.myback.utils.JwtTokenUtil;
import com.fei.myback.utils.RedisUtils;
import com.fei.myback.utils.ResoultType;
import com.fei.myback.utils.ResultEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@Api(tags = "用户接口")
public class LoginController {

    @Value("${jwt.Expiration}")
    public long outTime;

    @Autowired
    private UserServiceImpl userService;

    @Autowired
    private RedisUtils redisUtils;


    @PostMapping("/login")
    @ApiOperation(value = "登录接口", notes = "如在当前页面测试接口时，请在登录后把jwttoken放入左侧菜单栏第二个菜单中，在文本框中输入Bearer+空格+jwttoken")
    public String login(@RequestParam("username") String username, @RequestParam("password") String password) {
        log.info("登录认证");
        if (username != "" && password != "") {
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            UserDetails userDetails = userService.loadUserByUsername(username);
            if (userDetails != null && bCryptPasswordEncoder.matches(password, userDetails.getPassword())) {
                Map<String, Object> claims = new HashMap<>();
                claims.put("username", username);
                claims.put("startTime", System.currentTimeMillis());
                String jwtToken = JwtTokenUtil.generateToken(username, claims, outTime);
                return JSON.toJSONString(ResoultType.result(ResultEnum.USER_LOGIN_SUCCESS, jwtToken, true));
            }
        }
        return JSON.toJSONString(ResoultType.result(ResultEnum.USER_LOGIN_FAILED, false));
    }

    @ApiOperation(value = "用户登出", notes = "此处未作处理，只返回结果，前端自行删除token即可")
    @GetMapping("/logout")
    public String logout() {
        log.info("用户登出");
        return JSON.toJSONString(ResoultType.result(ResultEnum.USER_LOGOUT_SUCCESS, false));
    }

    @ApiOperation(value = "查询所有用户信息")
    @GetMapping("/selUsers")
    public String selUsers() {
        log.info("查询所有用户信息");
        Object str = redisUtils.get("users");
        if (str == null) {
            log.info("从数据库中获取所有用户");
            List<User> getusers = userService.getusers();
            str = getusers;
            redisUtils.set("users", JSON.toJSONString(str), 3L, TimeUnit.MINUTES);
            log.info("数据插入缓存" + str);
        }
        return JSON.toJSONString(ResoultType.result(ResultEnum.SUCCESS, str, true));
    }

    @ApiOperation(value = "获取指定用户信息")
    @GetMapping("/seluser/{username}")
    public String seluser(@PathVariable("username") String username) {
        log.info("获取指定用户信息");
        //查询缓存中是否存在
        Object str = redisUtils.get(username);
        if (str == null) {
            //从数据库中获取信息
            log.info("从数据库中获取数据" + username);
            User user = userService.getuser(username);
            user.setPassword(null);
            str = user;
            redisUtils.set(username, JSON.toJSONString(str), 10L, TimeUnit.MINUTES);
            log.info("数据插入缓存" + str);
        }
        return JSON.toJSONString(ResoultType.result(ResultEnum.SUCCESS, str, true));
    }

    @ApiOperation(value = "查询当前用户信息")
    @GetMapping("/selCurrentUser")
    public String selCurrentUser(HttpServletRequest request) {
        log.info("查询当前用户信息");
        Object str = redisUtils.get("selCurrentUser");
        if (str == null) {
            String info = JwtTokenUtil.parseToken(request.getHeader("Authorization").substring("Bearer ".length()));
            log.info("从数据库查询当前用户{}的信息", info);
            User user = userService.getuser(info);
            str = user;
            redisUtils.set(info, JSON.toJSONString(str), 10L, TimeUnit.MINUTES);
            user.setPassword(null);

        }
        return JSON.toJSONString(ResoultType.result(ResultEnum.SUCCESS, str, true));
    }

    @ApiOperation(value = "修改当前用户密码")
    @PostMapping("/DesignPassword")
    public String DesignCurrentUser(@RequestParam("username") String username, @RequestParam("password") String password,
                                    @RequestParam("newpassword") String newpassword) {
        log.info("修改当前用户信息");
        int i = userService.designUser(username, password, newpassword);
        if (i==0){
            Map<String,Object> map = new HashMap<>();
            map.put("message","原密码不正确");
            return JSON.toJSONString(ResoultType.result(ResultEnum.FAILURE,map, false));
        }
        return JSON.toJSONString(ResoultType.result(ResultEnum.SUCCESS, true));
    }

}
